package com.bdilab.iot.service.impl;

import com.bdilab.iot.dao.UserMapper;
import com.bdilab.iot.model.Permission;
import com.bdilab.iot.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/7/31 17:04
 * Spring Security 加载用户权限
 */
@Service("customerUserDetailService")
@Primary
public class UserDetailService implements UserDetailsService {

    @Resource
    UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUserName(username);
        if(user == null || (!user.isActive())){
            throw new  UsernameNotFoundException("用户名: "+username+" 不存在!");
        }
        List<Permission> permissions = userMapper.getPermissionById(user.getId());

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();


        // 超级管理员 权限
        if(user.getUsername().equals("admin")&&user.getId() == 1){
            grantedAuthorities.add(new SimpleGrantedAuthority("超级管理员"));
        }

        permissions.stream().filter(Objects::nonNull).forEach(p ->{
            if (p.getName() != null && !"".equals(p.getName())){
                grantedAuthorities.add(new SimpleGrantedAuthority(p.getName()));

            }
        });

        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                grantedAuthorities);

    }



}
